var fs = require('fs');

var LineByLineReader = require('line-by-line');

var map = new Map();

var inputFileName = 'care_teams.csv';
var outputFileName = 'result.csv';

function getDoctorPairWithNameCompare(name1, name2) {
    if (name1 > name2) {
        return name2+','+name1;
    }
    else {
        return name1+','+name2;
    }
}


var t1 = new Date().getTime();
console.log('start process on ' + t1);
lr = new LineByLineReader(inputFileName);

fs.existsSync(outputFileName, function(){
    fs.unlink(outputFileName);
});

lr.on('error', function (err) {
	console.log(err);
});

lr.on('line', function (line) {
	var names = line.split(',');

    var tmpMap = new Map();

    for (var i = 0; i < names.length; i++)
    {
        for (var j = i+1; j < names.length; j++)
        {
            if (names[i] != undefined && names[i] != "" && names[j] != undefined && names[j] != "")
            {
                var key = getDoctorPairWithNameCompare(names[i],names[j]);
                if(tmpMap.has(key))
                {
                    continue;
                }
                tmpMap.set(key,1);
            }

            if(map.has(key))
            {
                var currentNumber = map.get(key);
                currentNumber++;
                map.set(key,currentNumber);
            }
            else
            {
                map.set(key,1);
            }

        }
    }

    tmpMap.clear();
});

lr.on('end', function () {
    var str = "";
    map.forEach(function(value, key)
    {
      if (value >= 40)
      {
          console.log('key=' + key);
          str += key;
          str+='\r\n';
      }
    }, map);

    fs.writeFile(outputFileName,str);
    var t2 = new Date().getTime();
    console.log('end process on ' + t2);
    console.log('total cost time is  ' + (t2-t1));
});
